import Vue from 'vue'
import Toast from './Toast.vue';

const appendElement = (instanceCpt) => {
    // 在文档之外渲染并且随后挂载
    let msgBoxEl = instanceCpt.$mount().$el;
    /* 如果没有提供 elementOrSelector 参数，模板将被渲染为文档之外的的元素，
       并且你必须使用原生 DOM API 把它插入文档中。*/
    document.body.appendChild(msgBoxEl);
}

// 构造实例
const initCpt = (Vue, cpt) => {
    let CptInstance = Vue.extend(cpt);
    // 实例化vue实例
    let instanceCpt = new CptInstance();
    appendElement(instanceCpt);
    return instanceCpt
}

// 定义插件对象
const currentMsg = (options) => {
        if (Vue.prototype.$isServer) return;
        // 初始化构建实例
        let instance = initCpt(Vue, Toast);
        // 判断options
        if (typeof options === 'string') {
            instance.msg = options;
        } else if (typeof options === 'object') {
            Object.assign(instance, options);
        }
        // 显示toast
        instance.visible = true;
        return instance;
    }
    // // 构建状态方法
    ['success', 'warning', 'info', 'error'].forEach(type => {
        currentMsg[type] = options => {
            if (typeof options === 'string') {
                options = {
                    msg: options
                };
            }
            options.type = type;
            return currentMsg(options)
        };
    });
let instanceLoad;
currentMsg['loading'] = function() {
    if (!instanceLoad) {
        instanceLoad = initCpt(Vue, Toast);
        instanceLoad.loading = true;
    }
}
currentMsg['close'] = function() {
        if (instanceLoad) {
            instanceLoad.loading = false;
            instanceLoad = null;
        }
    }
    // vue的install方法，用于定义vue插件
const install = (Vue, config) => {
    Vue.prototype.$toast = currentMsg;
};

/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue);
}
export default {
    install, // 提供全局注册方法
    currentMsg // 提供按需导入组件
};